<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Auth;
use app\common\library\MyWeChat;
use EasyWeChat\Factory;

use addons\wechat\model\WechatCaptcha;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

use fast\Random;
use PDO;
use think\Response;
use think\cache\driver\Redis;
use think\Db;


/**
 * 微信相关
 */
class Wxchat extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';


    public function _initialize()
    {
        parent::_initialize();

        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'), '/');
        }

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = 30 * 86400;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);

            session("logined", 1);
            session("user", json_encode($user));
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());

            session("logined", 1);
            session("user", json_encode($user));
        });
    }

    /**
     * 授权登录
     */
    public function auth()
    {
        $wechat = new MyWeChat();
        $wechat->oauth_scopes();
    }

    /**
     * 授权登录-回调
     */
    public function auth_callback()
    {
        $code = input('code');
        $wechat = new MyWeChat();
        $userobj = $wechat->userFromCode($code);
        $wx_user = $userobj->toArray();
        // exit(print_r($wx_user));
        // exit(var_export($wx_user,true));

        /* $result 输出结果
         * Array (
            [id] => oaWII632e55s0ZuqCRQHsYQkMgFE
            [name] => 霍文霆
            [nickname] => 霍文霆
            [avatar] => https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJn6TuXOPKCAsrDl8SfriaZcaetY04blVTKVE0deman5ApWIOe6uPOXfK8Rq5MhEETaS1ulIE4whXQ/132
            [email] =>
            [raw] => Array (
                [openid] => oaWII632e55s0ZuqCRQHsYQkMgFE
                [nickname] => 霍文霆
                [sex] => 1
                [language] => zh_CN
                [city] =>
                [province] => 安徽
                [country] => 中国
                [headimgurl] => https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJn6TuXOPKCAsrDl8SfriaZcaetY04blVTKVE0deman5ApWIOe6uPOXfK8Rq5MhEETaS1ulIE4whXQ/132
                [privilege] => Array ( )
            )
            [token] => 44_XMZF2a0HHwE7Z268c_Qoi44a75hIvvw9lQi6I072ws2lop22xcYXMHoKWoA_NOo0hFH18aeXDrLejOBPf75A0Q
            [access_token] => 44_XMZF2a0HHwE7Z268c_Qoi44a75hIvvw9lQi6I072ws2lop22xcYXMHoKWoA_NOo0hFH18aeXDrLejOBPf75A0Q
            [expires_in] => 7200
            [refresh_token] => 44_SAM1LhD3MrQZ-xYc6uDP6fvglzDhl82wI_k2GM8wbUlG-6AcR22pXflwMTIg5fTwmYYFRYZuGhzD3ZuHE894VA
            [openid] => oaWII632e55s0ZuqCRQHsYQkMgFE
            [scope] => snsapi_userinfo
        )*/
        $openid = $wx_user["id"];
        $avatar = $wx_user["avatar"];
        $nickname = $wx_user["nickname"];
        $name = $wx_user["name"];
        $gender = $wx_user["raw"]["sex"] ? 1 : 0;

        $update_data = [
            "openid" => $openid,
            "avatar" => $avatar,
            "nickname" => $nickname,
            "username" => $name,
            "gender" => $gender,

        ];
        // exit(print_r($update_data));

        session("wx_auth_info", json_encode($update_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));

        //从数据库读取这个用户信息
        // $db_user = db("user")->where("openid", $openid)->find();
        // if ($db_user) {
        //     $this->redirect("/index/user/index");
        // }
        //跳到首页
        $this->redirect("/index/index/index");
    }

    /**
     * 测试专用
     */
    public function test()
    {
        $wechat = new MyWeChat();
        $touser = "oxA2hxKDRmYkmogwCoND1HU103sU";
        $url = "http://" . $_SERVER["HTTP_HOST"] . "/index/team/audituser";
        $template_id = MyWeChat::TEMPLATE_ID_ORDER_SUCCESS;
        $data = [
            "thing1" => "会员 8000014 下单了",
            "amount2" => "200",
            "time4" => date("Y-m-d H:i:s"),
        ];
        $result = $wechat->sendTemplateMsg($touser, $url, $template_id, $data);
        //Array ( [errcode] => 0 [errmsg] => ok [msgid] => 3774866401098448896 ) 
        exit(print_r($result));
    }
}
